package reflectdemo;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class ReflectClassDemo {
    public static void reflectNewInstance(){
        Class<?> c1;
        try {
            c1=Class.forName("reflectdemo.Person");
            Person person=(Person)c1.newInstance();
            System.out.println(person);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    public static void reflectPrivateConstructor(){
        Class<?> c1;
        try {
            c1=Class.forName("reflectdemo.Person");
          Constructor<?> constructor=c1.getDeclaredConstructor(String.class,int.class);
          constructor.setAccessible(true);
            Person person=(Person)constructor.newInstance("海绵宝宝",15);
            System.out.println(person);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
    public static void reflectPrivateFiled()  {
        Class<?> c1;
        try {
            c1=Class.forName("reflectdemo.Person");
            Field field =c1.getDeclaredField("name");
            field.setAccessible(true);
            Person person=(Person)c1.newInstance();
            field.set(person,"小明");
            System.out.println(person);
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }

    }
    public static void main(String[] args) {
//        reflectNewInstance();
        //reflectPrivateConstructor();
        reflectPrivateFiled();
    }
}
